﻿using log4net;
using Microsoft.Win32;
using Newtonsoft.Json;
using SiliconSelect.Base;
using SiliconSelect.BLL;
using SiliconSelect.Common;
using SiliconSelect.ViewModels;
using SiliconSelect.Views.UserOperatorDialog;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Threading.Tasks.Dataflow;
using System.Windows;
using System.Windows.Controls;

namespace SiliconSelect.Views
{
    /// <summary>
    /// RecipeSettingView.xaml 的交互逻辑
    /// </summary>
    public partial class RecipeSettingView : UserControl
    {
        RecipeSetttingViewModel viewModel;
        public RecipeSettingView()
        {
            InitializeComponent();
            viewModel = new RecipeSetttingViewModel();
            DataContext = viewModel;
        }

        /// <summary>
        /// 料盒设定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BoxSettngClick(object sender, RoutedEventArgs e)
        {
            // 点击了料盒设定
            BoxSettings boxSetting = new BoxSettings();
            boxSetting.ShowDialog();
        }

        /// <summary>
        /// 点击导入按钮.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnImportClick(object sender, RoutedEventArgs e)
        {
            try
            {
                string importDir = viewModel.ImportRecipeDir!;
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Title = "请选择导入配方文件";
                dialog.Filter = "文档|*.csv;*.xls;*.xlsx";
                dialog.InitialDirectory = importDir;
                dialog.RestoreDirectory = true;
                dialog.ShowDialog(); // 显示对话框
                string filePath = dialog.FileName; // 获取选择文件的全路径名
                if (!string.IsNullOrEmpty(filePath))
                {
                    viewModel.ImportRecipeDir = Path.GetDirectoryName(filePath);
                    viewModel.ImportRecipeFile = Path.GetFileName(filePath);
                    List<string> updateFields = new List<string>();
                    List<string> updateVals = new List<string>();
                    updateFields.Add("RecipeImportDir");
                    updateFields.Add("RecipeImportFile");
                    updateVals.Add(viewModel.ImportRecipeDir!);
                    updateVals.Add(viewModel.ImportRecipeFile!);
                    LocalDataAccess.UpdateWorkingInfo(updateFields, updateVals);
                    viewModel.LoadRecipe(); // 加载工单.然后这些要保存到数据库中去,方便下次导入.
                }
                dialog.Reset();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogType.Exception, ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!));
                MessageBox.Show($"导入失败:{ex.Message}", "导入失败提示框", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 点击保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSaveClick(object sender, RoutedEventArgs e)
        {
            try
            {
                string filePath = Path.Combine(viewModel.ImportRecipeDir!, viewModel.ImportRecipeFile!);
                //DataTable table1 = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(viewModel.DetectedRuleList), (typeof(DataTable)))!;
                //DataTable table2 = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(viewModel.RecipeConfigList), (typeof(DataTable)))!;
                // 单独写一个写入工单的函数
                DataResult res = ExcelHelper.SaveRecipeDatatableToExcel(filePath, viewModel.DetectedRuleList, viewModel.RecipeConfigList);
                if (!res.State)
                {
                    MessageBox.Show($"配方保存失败: {res.Message}", "保存失败提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                else
                {
                    // 保存成功以后,要将这个文件,拷贝到生产目录中去.
                    File.SetAttributes(filePath, FileAttributes.Normal);
                    string productionPath = Path.Combine(GlobalValues.ProductionRecipeDir, viewModel.ImportRecipeFile!);
                    // 如果文件已存在,提示工人是否覆盖
                    if (!File.Exists(productionPath))
                    {
                        File.Copy(filePath, productionPath);
                        MessageBox.Show("保存成功!", "操作成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        var result = MessageBox.Show($"文件{viewModel.ImportRecipeFile}已经存在,是否覆盖掉原来的文件", "文件操作提示框", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                        if (result == MessageBoxResult.OK)
                        {
                            File.SetAttributes(productionPath, FileAttributes.Normal);
                            File.Delete(productionPath);
                            File.Copy(filePath, productionPath);
                            MessageBox.Show("保存成功!", "操作成功", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配方失败:{ex.Message}", "保存配方失败提示框", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导出配方
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExportClick(object sender, RoutedEventArgs e)
        {
            try
            {
                string exportDir = viewModel.ImportRecipeDir!;
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Title = "导出配方文件";
                dialog.Filter = "文档|*.csv;*.xls;*.xlsx";
                dialog.InitialDirectory = exportDir;
                dialog.CheckFileExists = false;
                dialog.RestoreDirectory = true;
                dialog.FileName = viewModel.ImportRecipeFile;
                dialog.ShowDialog(); // 显示对话框
                string filePath = dialog.FileName!; // 获取选择文件的全路径名
                if (!string.IsNullOrEmpty(filePath))
                {
                    if (File.Exists(filePath))
                    {
                        var result = MessageBox.Show($"文件{Path.GetFileName(filePath)}已经存在,是否覆盖掉原来的文件", "文件操作提示框", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                        if (result == MessageBoxResult.OK)
                        {
                            File.SetAttributes(filePath, FileAttributes.Normal);
                            File.Delete(filePath);
                        }
                        else
                        {
                            return;
                        }
                    }
                }

                // 1. 先把导入的文件拷贝到导出的文件中去.
                //FileOperateHelper.CreateAnEmptyFile(filePath);
                File.Copy(Path.Combine(viewModel.ImportRecipeDir!, viewModel.ImportRecipeFile!), filePath);

                // 先去判断这个文件是否存在
                DataResult res = ExcelHelper.SaveRecipeDatatableToExcel(filePath, viewModel.DetectedRuleList, viewModel.RecipeConfigList);
                if (res.State)
                {
                    MessageBox.Show("导出成功!", "操作成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show($"导出失败,{res.Message}", "操作失败提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                dialog.Reset();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogType.Exception, ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!));
                MessageBox.Show($"导出配方失败:{ex.Message}", "导出配方失败提示框", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
